<template>
	<view class="phone-code">
		<!-- @tap="$tools.throttle(getCode)" -->
		<view class="i-code"  :class="{disabled:isCountDown}">
			{{countDownOrGetCodeText}}
		</view>
	</view>
</template>

<script>
export default {
	name: 'phoneCode',
	props: {
		mobile: {
			type: String,
			default: ''
		},
		event: {
			type: String,
			default: ''
		},
	},
	data() {
		return {
			isCountDown:false,     //如倒计时,更改countDownOrGetCodeText
			countDownOrGetCodeText:"获取验证码",
			countTime:60,
			isOut:false,//去除定时
			timer:'',
		}
	},
	beforeDestroy() {
		this.isOut=true;
		// console.log('phoneCode 调一次')
		if(this.timer){
		    clearTimeout(this.timer);
		    this.timer=null;				
		}
	},
	methods: {
		countDown(){
		    if(this.isOut){
		        return;
		    }
		    // console.log('countDown定时一次')
		    this.countDownOrGetCodeText="重新获取("+this.countTime+")";
		    this.countTime--;
		    if (this.countTime > 0) {
		            this.timer=setTimeout(this.countDown, 1000);
		    }else{
		        this.countDownOrGetCodeText="获取验证码";
		        this.isCountDown=false;
		        this.countTime=60;
		    }
		},
		async getCode(){
		    // console.log('===',props.mobile)
		    if(! uni.$tools.match( this.mobile,'mobile')){
		        return;
		    }
		    if(this.isCountDown==true){
		        return;
		    }
		    this.isCountDown=true;
		    try{
		        await uni.$request('user.sms',{mobile:this.mobile,event:this.event});
		    }catch(err){
				// console.log('err---',err)
				uni.$tools.msg(err?.data?.msg || '网络繁忙，请稍后重试~')
		        this.isCountDown=false;
				this.countDownOrGetCodeText="获取验证码"
				this.countTime=60;
		    }
			if(this.isCountDown){
				this.countDown(); 
			}
		},
	}
}
</script>
<style lang="scss" scoped>
	.i-code{
		margin-left: auto;
		font-size: 26rpx;
		color: $base-color;
		&.disabled{
			color:#999;
		}
	}
</style>
